Page({
  data: {
    myFriends: [],
    friendRequests: [],
    friendTab: 'myFriends',
    baseURL: wx.getStorageSync('baseURL') + '/',
    userInfo: wx.getStorageSync('userSession') || {},
    chatList: [],
    chatForm: { content: '' },
    nowfid: 0,
    nowfpic: '',
    nowname: '',
    nowtablename: '',
    recordListIndex: 'i0',
    chatTimer: null,
    showChatFullScreen: false,
  },
  onLoad() {
    // 优先从全局变量和缓存获取userInfo
    let userInfo = (getApp().globalData.userInfo && getApp().globalData.userInfo.id) ? getApp().globalData.userInfo : wx.getStorageSync('userSession') || {};
    this.setData({ userInfo });
    this.getFriendList();
  },
  async getFriendList() {
    if (!this.data.userInfo || !this.data.userInfo.id) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    const page = require('../../api/index').page;
    let res = await page('chatfriend', {
      uid: this.data.userInfo.id
    });
    let myFriends = [];
    let friendRequests = [];
    for (let x in res.data.list) {
      if (res.data.list[x].type == 1) {
        myFriends.push(res.data.list[x]);
      } else if (res.data.list[x].type == 0) {
        friendRequests.push(res.data.list[x]);
      }
    }
    // 实时查每个好友的最新头像
    const baseURL = wx.getStorageSync('baseURL');
    const updatePic = async (arr) => {
      for (let item of arr) {
        await new Promise((resolve) => {
          wx.request({
            url: baseURL + '/chuangyezhe/query',
            method: 'GET',
            data: { id: item.fid },
            success: (res) => {
              if (res.data && res.data.code === 0 && res.data.data && res.data.data.touxiang) {
                item.picture = res.data.data.touxiang;
                resolve();
                return;
              }
              wx.request({
                url: baseURL + '/daoshi/query',
                method: 'GET',
                data: { id: item.fid },
                success: (res2) => {
                  if (res2.data && res2.data.code === 0 && res2.data.data && res2.data.data.touxiang) {
                    item.picture = res2.data.data.touxiang;
                    resolve();
                    return;
                  }
                  wx.request({
                    url: baseURL + '/fuzeren/query',
                    method: 'GET',
                    data: { id: item.fid },
                    success: (res3) => {
                      if (res3.data && res3.data.code === 0 && res3.data.data && res3.data.data.touxiang) {
                        item.picture = res3.data.data.touxiang;
                      }
                      resolve();
                    },
                    fail: resolve
                  });
                },
                fail: resolve
              });
            },
            fail: resolve
          });
        });
      }
      arr.forEach(item => {
        if (!item.picture) {
          item.picture = '/static/upload.png';
        }
      });
    };
    await updatePic(myFriends);
    await updatePic(friendRequests);
    // 拉取最近一条消息（如有消息表可在此补充真实数据）
    myFriends.forEach(item => {
      item.lastMsg = item.lastMsg || '暂无消息';
      item.lastMsgTime = item.lastMsgTime || '';
    });
    this.setData({
      myFriends,
      friendRequests
    });
  },
  onFriendTabChange(e) {
    this.setData({ friendTab: e.currentTarget.dataset.tab });
  },
  async confirmFriend(e) {
    const add = require('../../api/index').add;
    const deleteData = require('../../api/index').deleteData;
    const item = e.currentTarget.dataset.item;
    let _this = this.data;
    let _that = this;
    wx.showModal({
      title: '提示',
      content: '是否同意好友申请？',
      success: async function (obj) {
        if (obj.confirm) {
          await add('chatfriend', {
            uid: item.fid,
            fid: _this.userInfo.id,
            type: 1,
            tablename: wx.getStorageSync("nowTable"),
            name: wx.getStorageSync("nickname"),
            picture: _this.userInfo.touxiang,
          });
          await add('chatfriend', {
            fid: item.fid,
            uid: _this.userInfo.id,
            type: 1,
            tablename: item.tablename,
            name: item.name,
            picture: item.picture
          });
          await deleteData('chatfriend', [item.id]);
          _that.getFriendList();
          wx.showToast({
            title: '添加好友成功',
            icon: 'none'
          });
        }
      }
    });
  },
  async cancelFriend(e) {
    const deleteData = require('../../api/index').deleteData;
    const item = e.currentTarget.dataset.item;
    wx.showModal({
      title: '提示',
      content: '是否拒绝该好友申请？',
      success: async function (obj) {
        if (obj.confirm) {
          await deleteData('chatfriend', [item.id]);
          wx.showToast({
            title: '已拒绝',
            icon: 'none'
          });
          this.getFriendList();
        }
      }.bind(this)
    });
  },
  async chatClick(e) {
    const row = e.currentTarget.dataset.item;
    if (row.type == 0) return;
    let obj = {};
    obj['nowfid'] = row.fid;
    obj['nowfpic'] = row.picture;
    obj['nowname'] = row.name;
    obj['nowtablename'] = row.tablename;
    obj['showChatFullScreen'] = true;
    this.setData(obj);
    await this.getChatList();
    const compChat = this.selectComponent('#myChatFrame');
    if (compChat) compChat.showFrame();
  },
  async getChatList() {
    const mlist = require('../../api/index').mlist;
    let userInfo = this.data.userInfo;
    let res = await mlist('chatmessage', {
      page: 1,
      limit: 1000,
      uid: userInfo.id,
      fid: this.data.nowfid
    });
    let chatList = res?.data?.list || [];
    this.setData({ chatList });
    setTimeout(() => {
      this.setData({ recordListIndex: 'i' + (chatList.length - 1) });
    }, 0);
    if (this.data.chatTimer) clearTimeout(this.data.chatTimer);
    this.data.chatTimer = setTimeout(() => { this.getChatList(); }, 5000);
  },
  contentTap(e) {
    let chatForm = Object.assign({}, this.data.chatForm);
    chatForm['content'] = e.detail.value;
    this.setData({ chatForm });
  },
  async addChat() {
    const page = require('../../api/index').page;
    const add = require('../../api/index').add;
    let userInfo = this.data.userInfo;
    if (!this.data.chatForm.content) return;
    let res = await page('chatfriend', {
      uid: userInfo.id,
      fid: this.data.nowfid,
      type: 2
    });
    if (!res.data.list.length) {
      await add('chatfriend', {
        uid: userInfo.id,
        fid: this.data.nowfid,
        name: this.data.nowname,
        picture: this.data.nowfpic,
        type: 2,
        tablename: 'yonghu'
      });
      await add('chatfriend', {
        fid: userInfo.id,
        uid: this.data.nowfid,
        name: wx.getStorageSync('nickname'),
        picture: userInfo.touxiang,
        type: 2,
        tablename: wx.getStorageSync('nowTable')
      });
    }
    await add('chatmessage', {
      fid: this.data.nowfid,
      uid: userInfo.id,
      content: this.data.chatForm.content,
      format: 1
    });
    this.setData({ chatForm: { content: '' } });
    this.getChatList();
  },
  async uploadImage() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        const baseURL = wx.getStorageSync('baseURL');
        const token = wx.getStorageSync('token');
        if (!baseURL) {
          wx.showToast({
            title: '服务器地址未配置',
            icon: 'none'
          });
          console.error('baseURL is empty');
          return;
        }
        if (!token) {
          wx.showToast({
            title: '请重新登录',
            icon: 'none'
          });
          console.error('token is empty');
          return;
        }
        wx.uploadFile({
          url: `${baseURL}/file/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'Token': token
          },
          success: async function (uploadFileRes) {
            console.log('上传返回', uploadFileRes);
            let result;
            try {
              result = JSON.parse(uploadFileRes.data);
            } catch (e) {
              wx.showToast({
                title: '服务器返回异常',
                icon: 'none'
              });
              console.error('服务器返回非JSON', uploadFileRes.data);
              return;
            }
            if (result.code == 0) {
              // 上传成功后，作为图片消息发送
              const add = require('../../api/index').add;
              let userInfo = that.data.userInfo;
              await add('chatmessage', {
                fid: that.data.nowfid,
                uid: userInfo.id,
                content: 'file/' + result.file,
                format: 2 // 2代表图片
              });
              that.getChatList();
              wx.showToast({
                title: '图片发送成功',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: result.msg || '上传失败',
                icon: 'none',
                duration: 2000
              });
              console.error('上传失败', result);
            }
          },
          fail: function (err) {
            wx.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
            console.error('uploadFile fail', err);
          }
        });
      },
      fail: function (err) {
        wx.showToast({
          title: '未选择图片',
          icon: 'none'
        });
        console.error('chooseImage fail', err);
      }
    });
  },
  cancelMyChatShow() {
    this.setData({ showChatFullScreen: false });
    const compChat = this.selectComponent('#myChatFrame');
    if (compChat) compChat.hideFrame();
  },
}); 